package main

import (
	"fmt"
	"gitee.com/jn-qq/similarity"
	"github.com/xuri/excelize/v2"
	"log"
	"math"
	"sync"
	"time"
)

var inChan = make(chan string, 1000)
var sourceMap = make(map[string][]float64)
var intentionMap = make(map[string][]string)
var sourceMapLock = sync.Mutex{}

var simil *similarity.Similar

func similarDo(wg *sync.WaitGroup) {
	defer wg.Done()
	for intentionName := range inChan {
		log.Println("处理意图：", intentionName)
		var sourceList []float64
		var lastQuestion string
		for _, question := range intentionMap[intentionName] {
			source, err := simil.TextSimilarity(lastQuestion, question)
			if err != nil {
				source = math.NaN()
			}
			sourceList = append(sourceList, source)
			lastQuestion = question
			log.Println(intentionName, question, source)
		}
		sourceMapLock.Lock()
		sourceMap[intentionName] = sourceList
		sourceMapLock.Unlock()
	}
}

func main() {
	// 读取excel
	f, err := excelize.OpenFile("dd.xlsx")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	// 读取数据
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		panic(err)
	}
	// 创建意图列表
	var intentionKeys []string
	for _, row := range rows[1:] {
		if _, ok := intentionMap[row[0]]; !ok {
			intentionMap[row[0]] = []string{}
			intentionKeys = append(intentionKeys, row[0])
		}
		intentionMap[row[0]] = append(intentionMap[row[0]], row[1])
	}

	log.Println("共有意图数量：", len(intentionKeys))

	// 创建相似度对象
	simil, _ = similarity.NewSimilar()
	_ = simil.LoadStopWords()

	for _, intentionName := range intentionKeys {
		inChan <- intentionName
	}
	close(inChan)

	wait := new(sync.WaitGroup)
	for i := 0; i < 3; i++ {
		log.Println("启动协程:id-", i+1)
		wait.Add(1)
		go similarDo(wait)
	}
	wait.Wait()

	log.Println("写入文件")
	var newCol = []any{"相似度"}
	for _, key := range intentionKeys {
		for _, source := range sourceMap[key] {
			newCol = append(newCol, source)
		}
	}
	// 写入文件
	_ = f.SetSheetCol("Sheet1", "C1", &newCol)
	_ = f.Save()
}

func main1() {
	similar, _ := similarity.NewSimilar()
	_ = similar.LoadStopWords()
	startTime := time.Now()
	res, _ := similar.TextSimilarity("最近总是觉得我的手机流量不够用，有没有推荐的流量包？", "最近总是觉得我的手机流量不够用，有没有推荐的流量包")
	endTime := time.Since(startTime)
	fmt.Println(res, endTime)
}
